package com.qiall.gateway.service;

import com.alibaba.fastjson.JSON;
import com.qiall.bashutil.TelnetOperator;
import com.qiall.gateway.service.request.FindDubboServiceResponse;
import com.qiall.oms.ability.FindDubboService;
import com.qiall.oms.ability.request.FindDubboServiceRequest;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * 服务发现
 */
@Component
public class DubboServiceService {
    @DubboReference(version = "${dubbo.provider.version}")
    private FindDubboService findDubbService;

    /**
     * 发现服务
     *
     * @param service
     * @param group
     * @param method
     * @return
     */
    public FindDubboServiceResponse findDubboService(String service, String group, String version, String method) {
        FindDubboServiceRequest findDubboServiceRequest = new FindDubboServiceRequest();
        findDubboServiceRequest.setRequestService(service);
        findDubboServiceRequest.setServiceGroup(group);
        findDubboServiceRequest.setVersion(version);
        com.qiall.oms.ability.request.FindDubboServiceResponse findDubboServiceResponse = findDubbService.findBuddoService(findDubboServiceRequest);
        FindDubboServiceResponse findDubboServiceResponseRet = new FindDubboServiceResponse();
        findDubboServiceResponseRet.setService(service);
        findDubboServiceResponseRet.setIp(findDubboServiceResponse.getIp());
        findDubboServiceResponseRet.setPort(findDubboServiceResponse.getPort());
        findDubboServiceResponseRet.setVersion(version);
        findDubboServiceResponseRet.setMethod(method);
        return findDubboServiceResponseRet;
    }

    /**
     * 构建请求体
     */
    public String buildDubboInvokeData(FindDubboServiceResponse findDubboServiceResponse, String requestBody) {
        String invoke = "invoke " + findDubboServiceResponse.getService() + "." + findDubboServiceResponse.getMethod() + "(" +
                requestBody + ")";
        return invoke;
    }

    public Map<String, Object> invoke(String ip, Integer port, String invokeData) {
        TelnetOperator telnetOperator = new TelnetOperator();
        telnetOperator.login(ip, port);
        String rs = telnetOperator.sendCommand(invokeData);
        telnetOperator.distinct();
        try {
            String result = rs.split("result:")[1].split("elapsed:")[0];
            return JSON.parseObject(result, HashMap.class);
        } catch (Exception e) {
            Map<String, Object> map = new HashMap<>();
            map.put("data", rs);
        }
        return null;

    }

}
